package handler

import (
	"ear-hub/cache"
	"ear-hub/model"
	"ear-hub/pkg"
	"encoding/json"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}

	redis_login_key := "redis_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "错误三次",
		})
		return
	}

	var user model.User
	err := model.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.MD5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "错误三次,封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "登录失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return

}

func List(c *gin.Context) {

	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var shop []model.Shop

	redis_list_key := "redis_list"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		model.DB.Offset(offset).Limit(size).Find(&shop)
		jsonData, _ := json.Marshal(shop)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &shop)
	}

	var total int64
	model.DB.Model(&model.Shop{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表成功",
		"data":  shop,
		"total": total,
	})
	return

}

func Comment(c *gin.Context) {

	var shop []model.Shop

	redis_list_key := "redis_lists_"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		model.DB.Find(&shop)
		jsonData, _ := json.Marshal(shop)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &shop)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论成功",
		"data": shop,
	})
	return
}
